package server

import (
	"context"
	"course-srv/basic/config"
	l "course-srv/basic/init"
	__ "course-srv/basic/proto"
	"course-srv/handler/models"
	"encoding/json"
	"errors"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedCourseServer
}

// 用户登录注册
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var err error

	var user models.User
	if err = user.GetUserInfo(in.Mobile); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if user.ID == 0 {
		user = models.User{
			Mobile:   in.Mobile,
			Password: in.Password,
		}
		if err = user.Register(); err != nil {
			return nil, errors.New("用户注册失败")
		}
	} else {
		if user.Password != in.Password {
			return nil, errors.New("账号密码错误")
		}
	}

	return &__.LoginResp{
		Mobile:   user.Mobile,
		Password: user.Password,
		Status:   int64(user.Status),
	}, nil
}

// 功能列表
func (s *Server) GetFunctionList(_ context.Context, in *__.GetFunctionListReq) (*__.GetFunctionListResp, error) {

	var function models.Function
	list, err := function.GetFunctionList()
	if err != nil {
		return nil, errors.New("查询功能失败")
	}

	var funcList []*__.GetFunctionInfo

	//redis优化
	get := config.Rdb.Get(l.Ctx, "functionList").Val()

	if get == "" {
		for _, f := range list {
			funcList = append(funcList, &__.GetFunctionInfo{
				Title: f.Title,
			})
		}
		data, _ := json.Marshal(&funcList)

		config.Rdb.Set(l.Ctx, "functionList", data, time.Minute*30)

	} else {
		_ = json.Unmarshal([]byte(get), &funcList)
	}

	return &__.GetFunctionListResp{
		FunctionList: funcList,
	}, nil
}

// 隐藏功能
func (s *Server) HideFunction(_ context.Context, in *__.HideFunctionReq) (*__.HideFunctionResp, error) {
	var err error

	var function models.Function
	if err = function.GetFunctionById(int(in.FunctionId)); err != nil {
		return nil, errors.New("查询功能失败")
	}

	if function.ID == 0 {
		return nil, errors.New("该功能不存在")
	}

	if function.Status == 2 {
		function.Status = 1
		if err = function.UpdateFuncStatus(int(in.FunctionId)); err != nil {
			return nil, errors.New("该功能展示失败")
		}

	} else {
		function.Status = 2
		if err = function.UpdateFuncStatus(int(in.FunctionId)); err != nil {
			return nil, errors.New("该功能隐藏失败")
		}

		//将隐藏的功能存入redis
		config.Rdb.Set(l.Ctx, "hideFunc", function.Title, time.Minute*30)
	}

	return &__.HideFunctionResp{
		Status: int64(function.Status),
	}, nil
}

// 添加课程
func (s *Server) AddCourse(_ context.Context, in *__.AddCourseReq) (*__.AddCourseResp, error) {
	var err error

	//判断类型
	var courseType models.CourseType
	if err = courseType.GetCourseType(int(in.CourseTypeId)); err != nil {
		return nil, errors.New("查询课程分类失败")
	}

	if courseType.ID == 0 {
		return nil, errors.New("该课程分类不存在")
	}

	var course models.Course
	course = models.Course{
		CourseTypeId: int(in.CourseTypeId),
		Author:       in.Author,
		Title:        in.Title,
		Desc:         in.Desc,
		CoverUrl:     in.CoverUrl,
		Catalogue:    in.Catalogue,
	}
	if err = course.AddCourse(); err != nil {
		return nil, errors.New("添加课程失败")
	}

	return &__.AddCourseResp{
		CourseId: int64(course.ID),
	}, nil
}

// 课程列表
func (s *Server) GetCourseList(_ context.Context, in *__.GetCourseListReq) (*__.GetCourseListResp, error) {
	var err error

	//判断类型
	var courseType models.CourseType
	if err = courseType.GetCourseType(int(in.CourseTypeId)); err != nil {
		return nil, errors.New("查询课程分类失败")
	}

	if int64(courseType.ID) != in.CourseTypeId {
		return nil, errors.New("该课程分类不存在")
	}

	//判断用户是否登录
	var user models.User
	if err = user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("用户查询失败")
	}
	if in.Page >= 4 || user.ID == 0 {
		return nil, errors.New("您未登录")
	}

	var course models.Course
	list, _ := course.GetCourseList(int(in.Page), int(in.PageSize), int(in.CourseTypeId))

	var courseList []*__.GetCourseInfo
	for _, c := range list {
		courseList = append(courseList, &__.GetCourseInfo{
			CourseType: courseType.Name,
			Author:     c.Author,
			Title:      c.Title,
			Desc:       c.Desc,
			CoverUrl:   c.CoverUrl,
			Catalogue:  c.Catalogue,
		})
	}

	return &__.GetCourseListResp{
		CourseList: courseList,
	}, nil
}

// 课程详情
func (s *Server) GetCourseDetail(_ context.Context, in *__.GetCourseDetailReq) (*__.GetCourseDetailResp, error) {
	var err error

	var course models.Course
	if err = course.GetCourseDetail(int(in.CourseId)); err != nil {
		return nil, errors.New("查询课程失败")
	}

	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	var courseType models.CourseType
	if err = courseType.GetCourseType(course.CourseTypeId); err != nil {
		return nil, errors.New("查询课程分类失败")
	}

	return &__.GetCourseDetailResp{
		CourseType:  courseType.Name,
		Author:      course.Author,
		Title:       course.Title,
		Desc:        course.Desc,
		CoverUrl:    course.CoverUrl,
		Catalogue:   course.Catalogue,
		MemberPrice: float32(course.MemberPrice),
		Price:       float32(course.Price),
		PayUrl:      course.PayUrl,
	}, nil
}

// 收藏
func (s *Server) AddCollect(_ context.Context, in *__.AddCollectReq) (*__.AddCollectResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("查询用户失败")
	}

	if user.ID == 0 {
		return nil, errors.New("未登录")
	}

	var course models.Course
	if err = course.GetCourseDetail(int(in.CourseId)); err != nil {
		return nil, errors.New("查询课程失败")
	}

	if course.ID == 0 {
		return nil, errors.New("该课程不存在")
	}

	var collect models.Collect
	collect = models.Collect{
		UserId:   int(in.UserId),
		CourseId: int(in.CourseId),
	}
	if err = collect.AddCollect(); err != nil {
		return nil, errors.New("收藏失败")
	}

	return &__.AddCollectResp{
		CollectId: int64(collect.ID),
	}, nil
}

// 收藏列表
func (s *Server) GetCollectList(_ context.Context, in *__.GetCollectListReq) (*__.GetCollectListResp, error) {
	var err error

	var user models.User
	if err = user.GetUserById(int(in.UserId)); err != nil {
		return nil, errors.New("查询用户失败")
	}

	if user.ID == 0 {
		return nil, errors.New("未登录")
	}

	var collect models.Collect
	if err = collect.GetCollectDetail(int(in.UserId)); err != nil {
		return nil, errors.New("查询失败")
	}

	var course models.Course
	if err = course.GetCourseDetail(collect.CourseId); err != nil {
		return nil, errors.New("查询课程失败")
	}

	var courseType models.CourseType
	if err = courseType.GetCourseType(course.CourseTypeId); err != nil {
		return nil, errors.New("查询课程分类失败")
	}

	list, _ := collect.GetCollectList(int(in.UserId))

	var collectList []*__.GetCollectInfo
	for _, c := range list {
		collectList = append(collectList, &__.GetCollectInfo{
			CollectId:   int64(c.CourseId),
			CourseType:  courseType.Name,
			Author:      course.Author,
			Title:       course.Title,
			Desc:        course.Desc,
			CoverUrl:    course.CoverUrl,
			Catalogue:   course.Catalogue,
			MemberPrice: float32(course.MemberPrice),
			Price:       float32(course.Price),
			PayUrl:      course.PayUrl,
		})
	}

	return &__.GetCollectListResp{
		CollectList: collectList,
	}, nil
}
